package com.identify.app.module.home;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.blankj.utilcode.util.ToastUtils;
import com.gprinter.aidl.GpService;
import com.gprinter.command.EscCommand;
import com.gprinter.command.GpCom;
import com.gprinter.command.GpUtils;
import com.gprinter.io.GpDevice;
import com.gprinter.io.PortParameters;
import com.gprinter.save.PortParamDataBase;
import com.gprinter.service.GpPrintService;
import com.identify.app.R;
import com.identify.app.common.ui.SimpleActivity;
import com.identify.app.module.carnumbersdk.MemoryCameraActivity;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import com.identify.app.utils.CheckPermission;
import com.identify.app.utils.L;
import com.identify.app.utils.PermissionActivity;
import com.identify.app.utils.RxTimerUtil;
import com.kernal.plateid.RecogService;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;

/**
 * 主页
 *
 * @author joyson
 */
public class MainActivity extends SimpleActivity implements AMapLocationListener {
    @BindView(R.id.et_input_car_num)
    EditText et_input_car_num;
    @BindView(R.id.et_input_car_color)
    EditText et_input_car_color;
    @BindView(R.id.et_time_year)
    EditText et_time_year;
    @BindView(R.id.et_time_month)
    EditText et_time_month;
    @BindView(R.id.et_time_day)
    EditText et_time_day;
    @BindView(R.id.et_time_hour)
    EditText et_time_hour;
    @BindView(R.id.et_time_minute)
    EditText et_time_minute;
    @BindView(R.id.et_input_address)
    EditText et_input_address;
    @BindView(R.id.rb_type_big_custom)
    RadioButton rb_type_big_custom;
    @BindView(R.id.rb_type_big_goods)
    RadioButton rb_type_big_goods;
    @BindView(R.id.rb_type_moto)
    RadioButton rb_type_moto;
    @BindView(R.id.rb_type_small_custom)
    RadioButton rb_type_small_custom;
    @BindView(R.id.rb_type_small_goods)
    RadioButton rb_type_small_goods;
    @BindView(R.id.rb_type_other)
    RadioButton rb_type_other;
    @BindView(R.id.et_input_car_color_other)
    EditText et_input_car_color_other;
    @BindView(R.id.et_input_police_name)
    EditText et_input_police_name;
    @BindView(R.id.rb_color_yellow)
    RadioButton rb_color_yellow;
    @BindView(R.id.rb_color_black)
    RadioButton rb_color_black;
    @BindView(R.id.rb_color_blue)
    RadioButton rb_color_blue;
    @BindView(R.id.rb_color_other)
    RadioButton rb_color_other;
    @BindView(R.id.rg_group_1)
    RadioGroup rg_group_1;
    @BindView(R.id.rg_group_2)
    RadioGroup rg_group_2;
    @BindView(R.id.iv_take_car_pic)
    ImageView iv_take_car_pic;
    private final static String DEBUG_TAG = "MainActivity";
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    // 定位点坐标 默认坐标 latitude=35.875083#longitude=120.048712
    LatLng locLocation;
    //定位城市
    String localCity;
    private long exitTime = 0;
    public static int request_pick_car_number_code = 1;
    private StringBuilder cityBuild;
    private int mPrinterId = 0;
    static final String[] PERMISSION = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
            Manifest.permission.READ_EXTERNAL_STORAGE, // 读取权限
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.VIBRATE, Manifest.permission.INTERNET,
    };
    private GpService mGpService = null;
    private PrinterServiceConnection conn = null;
    private PortParameters mPortParam[] = new PortParameters[GpPrintService.MAX_PRINTER_CNT];
    public static final int REQUEST_ENABLE_BT = 2;
    public static final int REQUEST_CONNECT_DEVICE = 3;
    public static final int REQUEST_USB_DEVICE = 4;
    private String blueAddress = "00:11:22:33:44:55";
    private String blueName = "Inner Printer";
    //是否发现目标设备
    private boolean isHaveTargetDevice = false;
    //是否连接目标设备
    private boolean isConnectTargetDevice = false;
    //    private boolean isBlueOrUsb = false;//true蓝牙 false usb
    private PortParameters mPortParamItem;
    private List<String> usbList = new ArrayList<>();
    private int retryReconnectCount = 3;
    private int retryCurReconnectCount = 0;


    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("ServiceConnection", "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
            initPortParam();
            Log.e(DEBUG_TAG, "服务创建");
//            connectOrDisConnectToDevice(mPrinterId);  //打印参数错误
        }
    }

    @Override
    protected void initEventAndData() {
//        commonTheme();
        requestLocPermissions();
        initPrintService();
        registerDevBroadcast();
        RxTimerUtil.timer(300, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext(long number) {
                //先进行usb遍历，若没有设备搜索蓝牙设备
                mPortParam[mPrinterId].setPortType(PortParameters.USB);
//            mPortParamItem.setPortType(PortParameters.USB);
                getUsbDeviceList();
            }
        });

    }

    //getBluetoothDevice()
    public void getUsbDeviceList() {
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        // Get the list of attached devices
        HashMap<String, UsbDevice> devices = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = devices.values().iterator();
        int count = devices.size();
        Log.d(DEBUG_TAG, "usb设备的数量 " + count);
        if (count > 0) {
            while (deviceIterator.hasNext()) {
                UsbDevice device = deviceIterator.next();
                //  /dev/bus/usb/001/005
                String devicename = device.getDeviceName();
                Log.e(DEBUG_TAG, "遍历得到的usb设备名字：" + devicename);
//                mPortParam[mPrinterId].setUsbDeviceName(devicename);
                if (checkUsbDevicePidVid(device)) {
//                    mUsbDeviceArrayAdapter.add(devicename);
                    usbList.add(devicename);
                    mPortParam[mPrinterId].setUsbDeviceName(devicename);
                    checkAndConnect();
                }
            }
        } else {
            String noDevices = getResources().getText(R.string.none_usb_device)
                    .toString();
            Log.d(DEBUG_TAG, "没有发现usb设备：" + noDevices);
            ToastUtils.showLong("未发现有可连接的usb设备，正在尝试搜索蓝牙设备，请稍后...");
            //开启blue设备的搜索
            getBluetoothDevice();
//            mUsbDeviceArrayAdapter.add(noDevices);
        }
    }

    private void checkAndConnect() {
        if (CheckPortParamters(mPortParam[mPrinterId])) {
            PortParamDataBase database = new PortParamDataBase(this);
            database.deleteDataBase("" + mPrinterId);
            database.insertPortParam(mPrinterId, mPortParam[mPrinterId]);
            connectOrDisConnectToDevice(mPrinterId);
        } else {
            messageBox(getString(R.string.port_parameters_wrong));
        }
    }

    boolean checkUsbDevicePidVid(UsbDevice dev) {
        int pid = dev.getProductId();
        int vid = dev.getVendorId();
        boolean rel = false;
        if ((vid == 34918 && pid == 256) || (vid == 1137 && pid == 85)
                || (vid == 6790 && pid == 30084)
                || (vid == 26728 && pid == 256) || (vid == 26728 && pid == 512)
                || (vid == 26728 && pid == 256) || (vid == 26728 && pid == 768)
                || (vid == 26728 && pid == 1024) || (vid == 26728 && pid == 1280)
                || (vid == 26728 && pid == 1536)) {
            rel = true;
        }
        return rel;
    }

    private void initPrintService() {
        // bindService
        conn = new PrinterServiceConnection();
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    //寻求定位权限
    private void requestLocPermissions() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission
                .requestEach(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {
                               @Override
                               public void accept(Permission permission) throws Exception {
                                   if (permission.granted) {
                                       // 用户已经同意该权限
                                       requestLocation();
                                       L.d(permission.name + " is granted.");
                                   } else if (permission.shouldShowRequestPermissionRationale) {
                                       // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                       L.d(permission.name + " is denied. More info should be provided.");
                                   } else {
                                       // 用户拒绝了该权限，并且选中『不再询问』
                                       L.d(permission.name + " is denied.and never ask again");
                                   }
                               }
                           }
                );
    }

    private void requestLocation() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(5000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    @OnClick({R.id.et_input_car_num, R.id.btn_print, R.id.iv_take_car_pic})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_input_car_num:
                //没输入内容才会打开
                if (TextUtils.isEmpty(getEditInputText(et_input_car_num))) {
//                    jumpTakePic();
                    jumpVideoPic();
                }
                break;
            case R.id.iv_take_car_pic:
//                jumpTakePic();
                jumpVideoPic();
                break;
            case R.id.btn_print:
//                if (!isHaveTargetDevice) {
//                    ToastUtils.showShort("没有发现此蓝牙设备");
//                    return;
//                }
                if (!isConnectTargetDevice) {
                    ToastUtils.showShort("没有连接此打印设备");
                    return;
                }
                String editInputText = getEditInputText(et_input_car_num);
                if (TextUtils.isEmpty(editInputText)) {
                    ToastUtils.showShort("车牌号为空");
                    return;
                }
                sendReceipt();


                break;
        }
    }

    private String getEditInputText(EditText editText) {
        return editText.getText().toString().trim();
    }

    @OnCheckedChanged({R.id.rb_color_yellow, R.id.rb_color_blue, R.id.rb_color_black, R.id.rb_color_other, R.id.rb_type_big_custom,
            R.id.rb_type_big_goods, R.id.rb_type_moto, R.id.rb_type_small_custom, R.id.rb_type_small_goods, R.id.rb_type_other})
    public void onCheckedChanged(CompoundButton view, boolean isChecked) {
        switch (view.getId()) {
            case R.id.rb_color_yellow:
                break;
            case R.id.rb_color_blue:
                break;
            case R.id.rb_color_black:
                break;
            case R.id.rb_color_other:
                break;
            case R.id.rb_type_big_custom:
                rg_group_2.clearCheck();
                break;
            case R.id.rb_type_big_goods:
                rg_group_2.clearCheck();
                break;
            case R.id.rb_type_moto:
                rg_group_2.clearCheck();
                break;
            case R.id.rb_type_small_custom:
                rg_group_1.clearCheck();
                break;
            case R.id.rb_type_small_goods:
                rg_group_1.clearCheck();
                break;
            case R.id.rb_type_other:
                rg_group_1.clearCheck();
                break;
        }
    }

    //跳转到拍照识别界面
    public void jumpTakePic() {
        Intent cameraintent = new Intent(MainActivity.this, MemoryCameraActivity.class);
        if (Build.VERSION.SDK_INT >= 23) {
            CheckPermission checkPermission = new CheckPermission(MainActivity.this);
            if (checkPermission.permissionSet(PERMISSION)) {
                PermissionActivity.startActivityForResult(MainActivity.this, 0, "false", PERMISSION);
            } else {
                cameraintent.putExtra("camera", false);
                startActivityForResult(cameraintent, request_pick_car_number_code);
            }
        } else {
            cameraintent.putExtra("camera", false);
            startActivityForResult(cameraintent, request_pick_car_number_code);
        }
    }

    //跳转到视频拍摄界面
    public void jumpVideoPic(){
        Intent video_intent = new Intent();
        video_intent.putExtra("camera", true);
        //开启精准模式
        RecogService.recogModel = true;
        video_intent = new Intent(MainActivity.this,MemoryCameraActivity.class);
        if (Build.VERSION.SDK_INT >= 23) {
            CheckPermission checkPermission = new CheckPermission(MainActivity.this);
            if (checkPermission.permissionSet(PERMISSION)) {
                PermissionActivity.startActivityForResult(MainActivity.this,0,"true",  PERMISSION);
            } else {
                video_intent.setClass(getApplicationContext(), MemoryCameraActivity.class);
                video_intent.putExtra("camera", true);
                startActivityForResult(video_intent,request_pick_car_number_code);
            }
        } else {
            video_intent.setClass(getApplicationContext(), MemoryCameraActivity.class);
            video_intent.putExtra("camera", true);
            startActivityForResult(video_intent,request_pick_car_number_code);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == request_pick_car_number_code && resultCode == MemoryCameraActivity.result_pick_car_number_code) {
            String number = data.getStringExtra("number");
            String[] carNumber = number.split(";");//可能返回多个，用 ; 分割
            String color = data.getStringExtra("color");
            Log.e(DEBUG_TAG, "车牌号：" + number + "，颜色：" + color);
            if (TextUtils.isEmpty(number)){
                ToastUtils.showShort("未识别车牌信息");
                return;
            }
            et_input_car_num.setText(carNumber[0]);
            switch (color) {
                case "蓝":
                    rb_color_blue.setChecked(true);
                    break;
                case "黑":
                    rb_color_black.setChecked(true);
                    break;
                case "黄":
                    rb_color_yellow.setChecked(true);
                    break;

            }
        }
    }

    //获取精确定位
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                localCity = aMapLocation.getCity();//获取定位城市
//                Log.e(DEBUG_TAG,("获取定位位置：" + localCity);
                locLocation = new LatLng(aMapLocation.getLatitude(),
                        aMapLocation.getLongitude());
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                cityBuild = new StringBuilder();
//                cityBuild.append(aMapLocation.getProvince());
//                cityBuild.append(aMapLocation.getCity());
//                cityBuild.append(aMapLocation.getDistrict());
                cityBuild.append(aMapLocation.getStreet());
                et_input_address.setText(cityBuild.toString());
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
//                Time t=new Time(System.currentTimeMillis()); // or Time t=new Time("GMT+8"); 加上Time Zone资料
                // 取得系统时间。
//                int day = t.getDay();
//                int month = t.month;
//                int date = t.monthDay;
//                int hour = t.hour;
                df.format(date);//定位时间
                et_time_year.setText(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
                et_time_month.setText(String.valueOf(date.getMonth() + 1));

                et_time_day.setText(String.valueOf(Calendar.getInstance().get(Calendar.DATE)));
                et_time_hour.setText(String.valueOf(date.getHours()));
                et_time_minute.setText(String.valueOf(date.getMinutes()));
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - exitTime) < 2000) {
            super.onBackPressed();
            finish();
        } else {
            Toast.makeText(this, R.string.double_click_exit, Toast.LENGTH_SHORT).show();
            exitTime = currentTime;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //停止定位
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
            mlocationClient = null;
        }

        if (conn != null) {
            unbindService(conn); // unBindService
        }
        // Unregister broadcast listeners
        if (PrinterStatusBroadcastReceiver != null) {
            this.unregisterReceiver(PrinterStatusBroadcastReceiver);
        }
        if (mFindBlueToothReceiver != null) {
            this.unregisterReceiver(mFindBlueToothReceiver);
        }

        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }


    }

    //   -----------------------------device---------------------------------
    void connectOrDisConnectToDevice(int PrinterId) {
        mPrinterId = PrinterId;
        int rel = 0;
//        Log.e(DEBUG_TAG, "连接或不连接设备：" + String.valueOf(mPortParam[PrinterId].getPortOpenState()));
//        mPortParam[PrinterId].setPortType(PortParameters.BLUETOOTH);
        if (mPortParam[PrinterId].getPortOpenState() == false) {
            if (CheckPortParamters(mPortParam[PrinterId])) {
                try {
                    mGpService.closePort(mPrinterId);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                switch (mPortParam[PrinterId].getPortType()) {
                    case PortParameters.USB:
                        try {
                            Log.e(DEBUG_TAG, "usd设备：" + mPortParam[PrinterId].getUsbDeviceName());
                            rel = mGpService.openPort(PrinterId, mPortParam[PrinterId].getPortType(),
                                    mPortParam[PrinterId].getUsbDeviceName(), 0);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                    case PortParameters.ETHERNET:
                        Log.e(DEBUG_TAG, "网络设备：" + mPortParam[PrinterId].getIpAddr());
                        try {
                            rel = mGpService.openPort(PrinterId, mPortParam[PrinterId].getPortType(),
                                    mPortParam[PrinterId].getIpAddr(), mPortParam[PrinterId].getPortNumber());
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                    case PortParameters.BLUETOOTH:
                        Log.e(DEBUG_TAG, "蓝牙设备：" + mPortParam[PrinterId].getBluetoothAddr());
                        try {
                            rel = mGpService.openPort(PrinterId, mPortParam[PrinterId].getPortType(),
                                    mPortParam[PrinterId].getBluetoothAddr(), 0);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                }
                GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
                Log.e(DEBUG_TAG, "result :" + String.valueOf(r));
                if (r != GpCom.ERROR_CODE.SUCCESS) {
                    if (r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
                        mPortParam[PrinterId].setPortOpenState(true);
//                        Map<String, Object> map = mList.get(PrinterId);
//                        map.put(ListViewAdapter.STATUS, getString(R.string.cut));
//                        mList.set(PrinterId, map);
//                        mListViewAdapter.notifyDataSetChanged();
                    } else {
                        messageBox(GpCom.getErrorText(r));
                    }
                }
            } else {
                messageBox(getString(R.string.port_parameters_wrong));
            }
        } else {
            Log.d(DEBUG_TAG, "DisconnectToDevice ");
            setProgressBarIndeterminateVisibility(true);
//            SetLinkButtonEnable(ListViewAdapter.DISABLE);
//            Map<String, Object> map = mList.get(PrinterId);
//            map.put(ListViewAdapter.STATUS, getString(R.string.cutting));
//            mList.set(PrinterId, map);
//            mListViewAdapter.notifyDataSetChanged();
            try {
                mGpService.closePort(PrinterId);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private Boolean CheckPortParamters(PortParameters param) {
        boolean rel = false;
        int type = param.getPortType();
        if (type == PortParameters.BLUETOOTH) {
            if (!param.getBluetoothAddr().equals("")) {
                rel = true;
            }
        } else if (type == PortParameters.ETHERNET) {
            if ((!param.getIpAddr().equals("")) && (param.getPortNumber() != 0)) {
                rel = true;
            }
        } else if (type == PortParameters.USB) {
            if (!param.getUsbDeviceName().equals("")) {
                rel = true;
            }
        }
        return rel;
    }

    private void messageBox(String err) {
        Toast.makeText(getApplicationContext(), err, Toast.LENGTH_SHORT).show();
    }

    private void initPortParam() {
        try {//防止遍历i找不到
            boolean[] state = getConnectState();
            for (int i = 0; i < GpPrintService.MAX_PRINTER_CNT; i++) {
                PortParamDataBase database = new PortParamDataBase(this);
                mPortParam[i] = new PortParameters();
                mPortParam[i] = database.queryPortParamDataBase("" + i);
                mPortParam[i].setPortOpenState(state[i]);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public boolean[] getConnectState() {
        boolean[] state = new boolean[GpPrintService.MAX_PRINTER_CNT];
        for (int i = 0; i < GpPrintService.MAX_PRINTER_CNT; i++) {
            state[i] = false;
        }
        for (int i = 0; i < GpPrintService.MAX_PRINTER_CNT; i++) {
            try {
                if (mGpService.getPrinterConnectStatus(i) == GpDevice.STATE_CONNECTED) {
                    state[i] = true;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return state;
    }

    private BroadcastReceiver PrinterStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (GpCom.ACTION_CONNECT_STATUS.equals(intent.getAction())) {
                int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);
                int id = intent.getIntExtra(GpPrintService.PRINTER_ID, 0);
                int portType = mPortParam[id].getPortType();

                //重试连接不上的顺序 ：2-3-0 GpDevice.STATE_CONNECTING  STATE_CONNECTED  STATE_NONE
                if (type == GpDevice.STATE_CONNECTING) {
                    setProgressBarIndeterminateVisibility(true);
                    mPortParam[id].setPortOpenState(false);
//                    Map<String, Object> map;
                    Log.e(DEBUG_TAG, "设备连接中 2");
                    ToastUtils.showLong("设备连接中...");
                } else if (type == GpDevice.STATE_NONE) {
                    setProgressBarIndeterminateVisibility(false);
                    mPortParam[id].setPortOpenState(false);
//                    Map<String, Object> map;
                    isConnectTargetDevice = false;
                    ToastUtils.showLong("设备没有连接");
                    Log.e(DEBUG_TAG, "设备没有连接");
                    retryConnectDevice(portType);
                } else if (type == GpDevice.STATE_VALID_PRINTER) {// 有效的设备，表明连接
                    ToastUtils.showLong("设备已有效连接");
                    Log.e(DEBUG_TAG, "设备已有效连接");
                    setProgressBarIndeterminateVisibility(false);
                    mPortParam[id].setPortOpenState(true);
//                    Map<String, Object> map;
                    isConnectTargetDevice = true;
                    retryCurReconnectCount = 0;
                } else if (type == GpDevice.STATE_INVALID_PRINTER) {
                    setProgressBarIndeterminateVisibility(false);
                    messageBox("请使用 Gprinter设备!");
                    Log.e(DEBUG_TAG, "请使用 Gprinter设备!");
                } else if (type == GpDevice.STATE_CONNECTED) {//已连接
                    ToastUtils.showLong("设备正在尝试连接");
                    Log.e(DEBUG_TAG, "设备正在连接 3");
                }
            }
        }
    };

    private void retryConnectDevice(int portType) {
        if (retryReconnectCount == retryCurReconnectCount) {
            retryCurReconnectCount = 0;
            if (portType == PortParameters.USB) {
                getBluetoothDevice();
            }
        } else {
            retryCurReconnectCount++;
            //重试usb
//            if (portType == PortParameters.USB) {
            checkAndConnect();
//            }
        }
    }

    private void registerDevBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(GpCom.ACTION_CONNECT_STATUS);
        this.registerReceiver(PrinterStatusBroadcastReceiver, filter);
    }

    private BluetoothAdapter mBluetoothAdapter;

    public void getBluetoothDevice() {
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            messageBox("蓝牙不支持此设备");
        } else {
            // If BT is not on, request that it be enabled.
            // setupChat() will then be called during onActivityResult
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent,
                        REQUEST_ENABLE_BT);
            } else {
//                Intent intent = new Intent(MainActivity.this,
//                        BluetoothDeviceList.class);
//                startActivityForResult(intent,
//                        REQUEST_CONNECT_DEVICE);
                discoveryDevice();
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                this.registerReceiver(mFindBlueToothReceiver, filter);
                // Register for broadcasts when discovery has finished
                filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
                this.registerReceiver(mFindBlueToothReceiver, filter);


                // Get a set of currently paired devices 之前配对的设备
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                // If there are paired devices, add each one to the ArrayAdapter
                if (pairedDevices.size() > 0) {
                    for (BluetoothDevice device : pairedDevices) {
                    }
                }
            }
        }
    }

    // changes the title when discovery is finished
    private final BroadcastReceiver mFindBlueToothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.e(DEBUG_TAG, "打印设备名字：" + device.getName() + "，打印设备地址：" + device.getAddress());
                if (!TextUtils.isEmpty(device.getName()) && device.getName().equals(blueName)) {//发现目标设备
                    isHaveTargetDevice = true;
                    //停止搜索
                    mBluetoothAdapter.cancelDiscovery();
                    mPortParam[mPrinterId].setPortType(PortParameters.BLUETOOTH);
                    //设置蓝牙设备地址
                    mPortParam[mPrinterId].setBluetoothAddr(device.getAddress());
                    checkAndConnect();
                }
                // If it's already paired, skip it, because it's been listed
                // already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
//                setProgressBarIndeterminateVisibility(false);
//                Log.i("tag", "finish discovery" +mNewDevicesArrayAdapter.getCount());
//                if (mNewDevicesArrayAdapter.getCount() == 0) {
//                    String noDevices = getResources().getText(
//                            R.string.none_bluetooth_device_found).toString();
//                    mNewDevicesArrayAdapter.add(noDevices);
//                }
            }
        }
    };

    private void discoveryDevice() {
        // If we're already discovering, stop it
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // Request discover from BluetoothAdapter
        mBluetoothAdapter.startDiscovery();
    }

    void sendReceipt() {
        EscCommand esc = new EscCommand();
        esc.addInitializePrinter();
//        esc.addInitializePrinter();
//        esc.addPrintAndFeedLines((byte) 3);
//        esc.addSelectJustification(JUSTIFICATION.CENTER);// 设置打印居中
//        esc.addSelectPrintModes(FONT.FONTA, ENABLE.OFF, ENABLE.ON, ENABLE.ON, ENABLE.OFF);// 设置为倍高倍宽
//        esc.addText("Sample\n"); // 打印文字
//        esc.addPrintAndLineFeed();
//
//        /* 打印文字 */
//        esc.addSelectPrintModes(FONT.FONTA, ENABLE.OFF, ENABLE.OFF, ENABLE.OFF, ENABLE.OFF);// 取消倍高倍宽
//        esc.addSelectJustification(JUSTIFICATION.LEFT);// 设置打印左对齐
        //⊙□选中未选中
        String car1;
        String car2;
        String car3;
        String car4;
        String car5;
        String car6;
        String colorYellow;
        String colorBlue;
        String colorBlack;
        String colorOther;

        StringBuilder builder = new StringBuilder();
        builder.append("车辆牌号：" + getEditInputText(et_input_car_num) + "车身颜色:" + getEditInputText(et_input_car_color) + "\n");
        String checkLogo="⊙";//⊙ ☑
        if (rb_type_big_custom.isChecked()) {
            car1 = checkLogo+"大型客车";
        } else {
            car1 = "□大型客车";
        }
        if (rb_type_small_custom.isChecked()) {
            car2 = checkLogo+"小型客车";
        } else {
            car2 = "□小型客车";
        }
        if (rb_type_big_goods.isChecked()) {
            car3 = checkLogo+"大型货车";
        } else {
            car3 = "□大型货车";
        }
        if (rb_type_small_goods.isChecked()) {
            car4 = checkLogo+"小型货车";
        } else {
            car4 = "□小型货车";
        }
        if (rb_type_moto.isChecked()) {
            car5 = checkLogo+"摩托车";
        } else {
            car5 = "□摩托车";
        }
        if (rb_type_other.isChecked()) {
            car6 = checkLogo+"其他";
        } else {
            car6 = "□其他";
        }
        if (rb_color_yellow.isChecked()) {
            colorYellow = checkLogo+"黄色";
        } else {
            colorYellow = "□黄色";
        }
        if (rb_color_blue.isChecked()) {
            colorBlue = checkLogo+"蓝色";
        } else {
            colorBlue = "□蓝色";
        }
        if (rb_color_black.isChecked()) {
            colorBlack = checkLogo+"黑色";
        } else {
            colorBlack = "□黑色";
        }
        if (rb_color_other.isChecked()) {
            colorOther = checkLogo+"其他";
        } else {
            colorOther = "□其他";
        }
        builder.append("车辆类型：" + car1 + " " + car2 + "\n");
        builder.append("          " + car3 + " " + car4 + "\n");
        builder.append("          " + car5 + "  " + car6 + getEditInputText(et_input_car_color_other) + "\n");
        builder.append("          " + car5 + "  " + car6 + getEditInputText(et_input_car_color_other) + "\n");
        builder.append("号牌颜色：" + colorYellow + colorBlue + colorBlack + colorOther + getEditInputText(et_input_car_color_other) + "\n");
        builder.append("  \n");
        builder.append("违法停车时间：" + getEditInputText(et_time_year) + "年" + getEditInputText(et_time_month) + "月" + getEditInputText(et_time_day) + "日" + getEditInputText(et_time_hour) + "时" + getEditInputText(et_time_minute) + "分" + "\n");
        builder.append("  \n");
        builder.append("违法停车地点：" + getEditInputText(et_input_address) + "\n");
        builder.append("  \n");
        builder.append(getString(R.string.traffic_police_hint) + "\n");
        builder.append("  \n");
        builder.append("交通警察：" + getEditInputText(et_input_police_name) + "\n");
        builder.append("--------------------------------" + "\n");
        builder.append(getString(R.string.traffic_police_remark) + "\n");
        builder.append("  " + "\n");
        builder.append("  " + "\n");

//        esc.addText("Print text\n"); // 打印文字
//        esc.addText("Welcome to use SMARNET printer!\n"); // 打印文字
//
//        /* 打印繁体中文 需要打印机支持繁体字库 */
//        String message = "佳博智匯票據打印機\n";
//        // esc.addText(message,"BIG5");
//        esc.addText(message, "GB2312");
//        esc.addPrintAndLineFeed();
//
//        /* 绝对位置 具体详细信息请查看GP58编程手册 */
//        esc.addText("智汇");
//        esc.addSetHorAndVerMotionUnits((byte) 7, (byte) 0);
//        esc.addSetAbsolutePrintPosition((short) 6);
//        esc.addText("网络");
//        esc.addSetAbsolutePrintPosition((short) 10);
//        esc.addText("设备");
//        esc.addPrintAndLineFeed();
//        esc.addTurnUnderlineModeOnOrOff(EscCommand.UNDERLINE_MODE.UNDERLINE_1DOT);
//        esc.addTurnUnderlineModeOnOrOff(EscCommand.UNDERLINE_MODE.OFF);

        esc.addText(builder.toString());

//        /* 打印图片 */
//        esc.addText("Print bitmap!\n"); // 打印文字
//        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.gprinter);
//        esc.addRastBitImage(b, 110, 0); // 打印图片
//
//        esc.addText("家用车");
//        Bitmap b2 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_checked);
//        esc.addRastBitImage(b2, 18, 0); // 打印图片
//        esc.addText("\n");
//
//        Bitmap b3 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_unchecked);
//        esc.addRastBitImage(b3, 18, 0); // 打印图片
//        esc.addText("客运汽车\n");
//
//        esc.addText("这是");
//        Bitmap b4 =BitmapFactory.decodeResource(getResources(), R.drawable.seekbar_thump_pic);
//        esc.addRastBitImage(b4, 55, 0); // 打印图片
//        esc.addText("客运汽车\n");
//        esc.addText("     \n");
//        esc.addText("     \n");
//        esc.addText("     \n");
//
//        /* 打印一维条码 */
//        esc.addText("Print code128\n"); // 打印文字
//        esc.addSelectPrintingPositionForHRICharacters(HRI_POSITION.BELOW);//
//        // 设置条码可识别字符位置在条码下方
//        esc.addSetBarcodeHeight((byte) 60); // 设置条码高度为60点
//        esc.addSetBarcodeWidth((byte) 1); // 设置条码单元宽度为1
//        esc.addCODE128(esc.genCodeB("SMARNET")); // 打印Code128码
//        esc.addPrintAndLineFeed();
//
//        /*
//         * QRCode命令打印 此命令只在支持QRCode命令打印的机型才能使用。 在不支持二维码指令打印的机型上，则需要发送二维条码图片
//         */
//        esc.addText("Print QRcode\n"); // 打印文字
//        esc.addSelectErrorCorrectionLevelForQRCode((byte) 0x31); // 设置纠错等级
//        esc.addSelectSizeOfModuleForQRCode((byte) 3);// 设置qrcode模块大小
//        esc.addStoreQRCodeData("www.smarnet.cc");// 设置qrcode内容
//        esc.addPrintQRCode();// 打印QRCode
//        esc.addPrintAndLineFeed();
//
//        /* 打印文字 */
//        esc.addSelectJustification(JUSTIFICATION.CENTER);// 设置打印左对齐
//        esc.addText("Completed!\r\n"); // 打印结束
//        // 开钱箱
//        esc.addGeneratePlus(LabelCommand.FOOT.F5, (byte) 255, (byte) 255);
//        esc.addPrintAndFeedLines((byte) 8);
//
        Vector<Byte> datas = esc.getCommand(); // 发送数据
        byte[] bytes = GpUtils.ByteTo_byte(datas);
        String sss = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rs;
        try {
            rs = mGpService.sendEscCommand(mPrinterId, sss);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rs];

            if (r != GpCom.ERROR_CODE.SUCCESS) {
                Toast.makeText(getApplicationContext(), GpCom.getErrorText(r), Toast.LENGTH_SHORT).show();
            } else {
                //发送成功
                Log.e(DEBUG_TAG, "发送成功");
//                ToastUtils.showShort("发送成功");
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
